package pkg

import (
	"errors"
	"fmt"
	"log"
	"sync"

	"github.com/gin-gonic/gin"
)

type Server struct {
	Port          int
	VideoPathList []string
	Service       *gin.Engine
}

func NewServer(port int, videoPathList []string) *Server {

	Service := gin.New()

	return &Server{
		Port:          port,
		VideoPathList: videoPathList,
		Service:       Service,
	}
}

func (s *Server) Len() int {
	return len(s.VideoPathList)
}

type SubServerPool struct {
	Pool []*Server
}

func NewSubServerPool(videoPathGroup [][]string, portPool *PortPool) (*SubServerPool, error) {

	if len(videoPathGroup) != len(portPool.Pool) {
		return nil, errors.New("videoPathGroup.lenthg != portPool.length")
	}

	ssp := &SubServerPool{}

	for index, item := range videoPathGroup {

		server := NewServer(portPool.Pool[index], item)
		mid := videoListMiddle(server)

		server.Service.Use(mid)
		ssp.Pool = append(ssp.Pool, server)
	}

	return ssp, nil

}

func (s *SubServerPool) Run(wg *sync.WaitGroup) {

	for _, server := range s.Pool {

		wg.Add(1)

		go func() {
			defer wg.Done()
			log.Println(fmt.Sprintf("video server: %d", server.Port))
			server.Service.Run(fmt.Sprintf(":%d", server.Port))
		}()

	}

}

func videoListMiddle(s *Server) gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Set("server", s)
		c.Next()
	}
}
